<template>
  <div class="data-analysis">
    <el-row :gutter="20">
      <!-- 数据概览卡片 -->
      <el-col :span="6" v-for="card in dataCards" :key="card.title">
        <el-card class="data-card" :body-style="{ padding: '20px' }">
          <div class="card-content">
            <div class="card-icon" :style="{ background: card.color }">
              <el-icon><component :is="card.icon" /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">{{ card.title }}</div>
              <div class="card-value">{{ card.value }}</div>
              <div class="card-trend" :class="{ 'up': card.trend > 0, 'down': card.trend < 0 }">
                较上月{{ Math.abs(card.trend) }}%
                <el-icon><component :is="card.trend > 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 身高分布饼图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>儿童身高分布</span>
              <el-radio-group v-model="heightChartType" size="small">
                <el-radio-button value="pie">饼图</el-radio-button>
                <el-radio-button value="bar">柱状图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="heightChartRef"></div>
        </el-card>
      </el-col>

      <!-- 体重分布图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>儿童体重分布</span>
              <el-radio-group v-model="weightChartType" size="small">
                <el-radio-button value="pie">饼图</el-radio-button>
                <el-radio-button value="bar">柱状图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="weightChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- BMI指数分布 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>BMI指数分布</span>
              <el-select v-model="bmiAgeGroup" size="small" style="width: 120px">
                <el-option value="3-6" label="3-6岁" />
                <el-option value="7-12" label="7-12岁" />
                <el-option value="13-16" label="13-16岁" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="bmiChartRef"></div>
        </el-card>
      </el-col>

      <!-- 年龄分布 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>年龄分布</span>
            </div>
          </template>
          <div class="chart-container" ref="ageChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { 
  User, 
  DataLine, 
  TrendCharts,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { getDataAnalysis } from '@/api/statistics'
import { ElMessage } from 'element-plus'

// 数据概览卡片
const dataCards = ref([
  {
    title: '总用户数',
    value: '0',
    trend: 0,
    icon: 'User',
    color: 'linear-gradient(135deg, #36D1DC 0%, #5B86E5 100%)'
  },
  {
    title: '本月新增',
    value: '0',
    trend: 0,
    icon: 'DataLine',
    color: 'linear-gradient(135deg, #FF9A9E 0%, #FAD0C4 100%)'
  },
  {
    title: '平均身高',
    value: '0cm',
    trend: 0,
    icon: 'TrendCharts',
    color: 'linear-gradient(135deg, #43E97B 0%, #38F9D7 100%)'
  },
  {
    title: '平均体重',
    value: '0kg',
    trend: 0,
    icon: 'TrendCharts',
    color: 'linear-gradient(135deg, #FA709A 0%, #FEE140 100%)'
  }
])

// 图表类型
const heightChartType = ref('pie')
const weightChartType = ref('pie')
const bmiAgeGroup = ref('3-6')

// 图表实例
let heightChart = null
let weightChart = null
let bmiChart = null
let ageChart = null

// 图表容器引用
const heightChartRef = ref(null)
const weightChartRef = ref(null)
const bmiChartRef = ref(null)
const ageChartRef = ref(null)

// 图表数据
const heightData = ref([])
const weightData = ref([])
const bmiData = ref([])
const ageData = ref([])

// 获取所有数据
const fetchAllData = async () => {
  try {
    const data = await getDataAnalysis()
    console.log('API响应:', data) // 调试日志
    
    if (data) {
      // 更新数据卡片
      dataCards.value[0].value = (data.totalUsers || 0).toLocaleString()
      dataCards.value[0].trend = data.monthlyGrowthRate || 0
      dataCards.value[1].value = (data.monthlyNewUsers || 0).toLocaleString()
      dataCards.value[1].trend = data.monthlyGrowthRate || 0
      dataCards.value[2].value = `${(data.averageHeight || 0).toFixed(1)}cm`
      dataCards.value[2].trend = 0 // 暂时不显示趋势
      dataCards.value[3].value = `${(data.averageWeight || 0).toFixed(1)}kg`
      dataCards.value[3].trend = 0 // 暂时不显示趋势
      
      // 更新图表数据，添加默认值处理
      const defaultDistribution = [0,0,0,0,0]
      
      // 转换身高分布数据
      const heightLabels = ['<80cm', '80-100cm', '100-120cm', '120-140cm', '>140cm']
      heightData.value = transformDistributionData(data.heightDistribution || defaultDistribution, heightLabels)
      
      // 转换体重分布数据
      const weightLabels = ['<10kg', '10-20kg', '20-30kg', '30-40kg', '>40kg']
      weightData.value = transformDistributionData(data.weightDistribution || defaultDistribution, weightLabels)
      
      // 转换BMI分布数据
      const bmiLabels = ['<14', '14-16', '16-18', '18-20', '>20']
      bmiData.value = transformDistributionData(data.bmiDistribution || defaultDistribution, bmiLabels)
      
      // 转换年龄分布数据
      const ageLabels = ['0-1岁', '1-3岁', '3-6岁', '6-12岁', '>12岁']
      ageData.value = transformDistributionData(data.ageDistribution || defaultDistribution, ageLabels)
      
      // 初始化所有图表
      nextTick(() => {
        initHeightChart()
        initWeightChart()
        initBMIChart()
        initAgeChart()
      })
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error.message || '获取数据失败')
  }
}

// 转换分布数据为图表所需格式
const transformDistributionData = (distribution, labels) => {
  if (!distribution || !Array.isArray(distribution)) return []
  return distribution.map((value, index) => ({
    name: labels[index],
    value: value || 0
  }))
}

// 初始化身高分布图表
const initHeightChart = () => {
  if (!heightChartRef.value || !heightData.value.length) return
  
  heightChart = echarts.init(heightChartRef.value)
  const options = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    series: [
      {
        type: heightChartType.value,
        radius: heightChartType.value === 'pie' ? ['40%', '70%'] : undefined,
        center: ['50%', '40%'],
        data: heightData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    color: ['#36D1DC', '#5B86E5', '#FF9A9E', '#FAD0C4']
  }

  if (heightChartType.value === 'bar') {
    options.xAxis = {
      type: 'category',
      data: heightData.value.map(item => item.name)
    }
    options.yAxis = {
      type: 'value',
      name: '人数'
    }
  }

  heightChart.setOption(options)
}

// 初始化体重分布图表
const initWeightChart = () => {
  if (!weightChartRef.value || !weightData.value.length) return
  
  weightChart = echarts.init(weightChartRef.value)
  const options = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    series: [
      {
        type: weightChartType.value,
        radius: weightChartType.value === 'pie' ? ['40%', '70%'] : undefined,
        center: ['50%', '40%'],
        data: weightData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    color: ['#43E97B', '#38F9D7', '#FA709A', '#FEE140']
  }

  if (weightChartType.value === 'bar') {
    options.xAxis = {
      type: 'category',
      data: weightData.value.map(item => item.name)
    }
    options.yAxis = {
      type: 'value',
      name: '人数'
    }
  }

  weightChart.setOption(options)
}

// 初始化BMI分布图表
const initBMIChart = () => {
  if (!bmiChartRef.value || !bmiData.value.length) return
  
  bmiChart = echarts.init(bmiChartRef.value)
  bmiChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '人数',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: bmiData.value.map(item => item.name)
    },
    series: [
      {
        type: 'bar',
        data: bmiData.value.map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#36D1DC' },
            { offset: 1, color: '#5B86E5' }
          ])
        }
      }
    ]
  })
}

// 初始化年龄分布图表
const initAgeChart = () => {
  if (!ageChartRef.value || !ageData.value.length) return
  
  ageChart = echarts.init(ageChartRef.value)
  ageChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '40%'],
        data: ageData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    color: ['#FF9A9E', '#FAD0C4', '#43E97B']
  })
}

// 监听图表类型变化
watch([heightChartType, weightChartType], () => {
  initHeightChart()
  initWeightChart()
})

// 监听窗口大小变化
const handleResize = () => {
  heightChart?.resize()
  weightChart?.resize()
  bmiChart?.resize()
  ageChart?.resize()
}

onMounted(() => {
  fetchAllData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  heightChart?.dispose()
  weightChart?.dispose()
  bmiChart?.dispose()
  ageChart?.dispose()
})
</script>

<style scoped>
.data-analysis {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.chart-row {
  margin-top: 20px;
}

.data-card {
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.data-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.card-icon .el-icon {
  font-size: 24px;
  color: #fff;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.card-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-trend.up {
  color: #67c23a;
}

.card-trend.down {
  color: #f56c6c;
}

.chart-card {
  border-radius: 8px;
  overflow: hidden;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.chart-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 400px;
  padding: 20px;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style> 